package com.zhuiyun.project.api.group.service.impl;

import com.zhuiyun.project.api.appuser.entity.User;
import com.zhuiyun.project.api.appusermessage.service.DiseaseService;
import com.zhuiyun.project.api.group.entity.Group;
import com.zhuiyun.project.api.group.mapper.GroupMapper;
import com.zhuiyun.project.api.group.model.GroupModel;
import com.zhuiyun.project.api.group.service.GroupService;
import com.zhuiyun.project.api.groupmessage.model.GroupMessageModel;
import com.zhuiyun.project.api.groupmessage.service.GroupMessageService;
import com.zhuiyun.project.api.joingroup.entity.JoinGroup;
import com.zhuiyun.project.api.joingroup.mapper.JoinGroupMapper;
import com.zhuiyun.project.api.joingroup.service.JoinGroupService;
import com.zhuiyun.project.api.message.config.DateConverter;
import com.zhuiyun.project.api.message.config.MessageType;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.BeanUtils;
import com.zhuiyun.project.util.ObjectUtils;
import com.zhuiyun.project.util.UploadFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName GroupServiceImpl
 * @Description TODO
 * @Author kdj
 * @Date 2023/7/24 10:00
 **/
@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private JoinGroupService joinGroupService;
    @Autowired
    private GroupMessageService messageService;
    @Autowired
    private DiseaseService diseaseService;
    @Autowired
    private JoinGroupMapper joinGroupMapper;

    /**
     * @param file
     * @param groupModel
     * @Author kdj
     * @Description 创建群聊
     * @Date 2023/7/24 10:56
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult createGroup(MultipartFile file, GroupModel groupModel) {
        //上传文件
        //判断图片文件是否为空
        if (file != null) {
            String s = UploadFileUtils.uploadAvatar(file);
            if (!ObjectUtils.isNotEmpty(s)) {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
            groupModel.setGroupImgId(Integer.parseInt(s));
        }
        Group group = new Group();
        // groupModel 对象拷贝成 group
        BeanUtils.copy(groupModel, group);
        //生成群号
        Long groupNum = generateUniqueNineDigit();
        group.setGroupNum(groupNum);
        group.setCreateTime(new Date());
        group.setUpdateTime(new Date());
        group.setDelFlag(0);
        //添加
        int i = groupMapper.insertSelective(group);
        //将该用户添加到joinGroup表中
        joinGroupService.addSysUserInJoinGroup(group.getCreateUserId(), group.getId(), null, MessageType.socketSysNum);
        if (i > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("groupNum", group.getGroupNum());
            map.put("groupId", group.getId());
            return CommonResult.ok(map);
        }
        return CommonResult.error(EmErrorCode.SAVE_ERROR);
    }

    /**
     * @param createUserId
     * @Author kdj
     * @Description 获取群聊根据创始人
     * @Date 2023/7/24 16:04
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult getGroupByCreateUserId(int createUserId) {
        List<Map> list = joinGroupService.queryGroupsDataByUserId(createUserId, MessageType.socketSysNum);
        //获取未读数 以及最新更新时间
        List<Map> maplist = list.stream().map(group -> {
                    //更新
                    Map map = new HashMap<>();
                    map.put("groupId", group.get("group_id"));
                    map.put("groupNum", group.get("group_num"));
                    map.put("groupName", group.get("group_name"));
                    map.put("groupImgId", group.get("group_img_id"));
                    GroupMessageModel groupId = messageService.getGroupChatLast((Integer) group.get("group_id"));
                    //判断存不存在最后一条数据
                    if (groupId != null) {
/*                        //判断groupId对象有没有被我删除
                        String deleteUserId = groupId.getDeleteUserId();
                        boolean isDeleted = false;
                        if (deleteUserId != null && deleteUserId.contains(",")) {
                            String[] split = deleteUserId.split(",");
                            if (split.length == 0) {
                                isDeleted = false;
                            }
                            for (String s : split) {
                                String typeText = MessageType.socketSysNum == MessageType.socketSysNum ? MessageType.socketSys : MessageType.socketApp;
                                if (s.equals(typeText + "_" + createUserId))
                                    isDeleted = true;
                                break;
                            }
                        }
                        //判断
                        if (isDeleted) {
                            LocalDateTime lastMessageTime = (LocalDateTime) group.get("last_message_time");
                            Instant instant = lastMessageTime.atZone(ZoneId.systemDefault()).toInstant();
                            Date date = Date.from(instant);
                            map.put("lastMessageTime", date);
                            map.put("lastMessageContent", group.get("last_message_content"));
                        } else {
                            map.put("lastMessageTime", groupId.getCreateTime());
                            map.put("lastMessageContent", groupId.getContent());
                        }*/
                        map.put("lastMessageTime", groupId.getCreateTime());
                        map.put("unReadNum", group.get("un_read_num"));
                    } else {
                        //一般都是 创始人 才走这个段代码
                        LocalDateTime lastMessageTime = (LocalDateTime) group.get("create_time");
                        Instant instant = lastMessageTime.atZone(ZoneId.systemDefault()).toInstant();
                        Date date = Date.from(instant);
                        map.put("lastMessageTime", date);
                        map.put("unReadNum", group.get("un_read_num"));
                    }
                    return map;
                }).sorted((h1, h2) -> ((Date) h2.get("lastMessageTime")).compareTo((Date) h1.get("lastMessageTime")))
                .map(map -> {
                    map.put("lastMessageTime", DateConverter.convertDateToString((Date) map.get("lastMessageTime")));
                    return map;
                }).collect(Collectors.toList());
        return CommonResult.ok(maplist);
    }

    /**
     * @param groupId
     * @Author kdj
     * @Description 根据groupId获取group对象
     * @Date 2023/7/24 19:55
     * @Return com.zhuiyun.project.api.group.entity.Group
     */
    @Override
    public Group getGroupByGroupId(int groupId) {
        return groupMapper.getGroupByGroupId(groupId);
    }

    /**
     * @param groupNum
     * @Author kdj
     * @Description 根据群号搜索到群
     * @Date 2023/7/25 20:28
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public Map queryGroupByNum(int groupNum, int userId, String type) {
        Group group = groupMapper.queryGroupByNum(groupNum);
        //根据该groupid判断是否添加过
        JoinGroup groupData = joinGroupService.getGroupData(userId, group.getId(), type.equals(MessageType.socketSys) ? MessageType.socketSysNum : MessageType.socketAppNum);
        Map<String, Object> map = new HashMap<>();
        //判断为不为空
        map.put("group", group);
        if (groupData == null) {
            map.put("isExist", false);
            map.put("isAudit", false);
        } else {
            map.put("isExist", true);
            //判断是不是在请求中
            if (groupData.getDelFlag() == 0 & groupData.getJoinStatus() == 0) {
                map.put("isAudit", true);
            } else {
                map.put("isAudit", false);
            }
        }


        return map;
    }

    /**
     * @param groupId
     * @Author kdj
     * @Description 根据群id搜索到群 获取群信息
     * @Date 2023/7/27 17:10
     * @Return java.lang.Object
     */
    @Override
    public GroupModel queryGroupByGroupId(int groupId) {
        //根据群id查询群成员总数
        int i = groupMapper.userCount(groupId);
        Group group = groupMapper.getGroupByGroupId(groupId);
        //根据病种类型获取 病种文字
        String diseaseLabel = diseaseService.getDiseaseLabel(group.getDiseaseId());
        GroupModel groupModel = new GroupModel();
        BeanUtils.copy(group,
                groupModel);
        groupModel.setDiseaseText(diseaseLabel);
        groupModel.setGroupCount(i);
        return groupModel;
    }

    /**
     * @param groupId
     * @Author kdj
     * @Description 获取创始人id
     * @Date 2023/7/27 19:49
     * @Return int
     */
    @Override
    public int getCreateUserId(int groupId) {
        return groupMapper.getCreateUserId(groupId);
    }

    /**
     * @param groupModel
     * @Author 韩佳轩
     * @Description 群聊首页信息
     * @Date 2023/7/26 21:48
     * @Return
     */
    @Override
    public List<GroupModel> queryAllGroup(GroupModel groupModel) {
        return groupMapper.queryAllGroup(groupModel);
    }
    /**
     * @Author 韩佳轩
     * @Description 修改头像和群名称
     * @Date 2023/7/27 19:26
     * @Return
     * @param group
     */
    @Override
    public int updateGroupAll(MultipartFile file,Group group) {
        if (file != null){
            String s = UploadFileUtils.uploadAvatar(file);
            group.setGroupImgId(Integer.valueOf(s));
        }
        int i = groupMapper.updateByPrimaryKeySelective(group);
        return i;
    }

    /**
     * @param userId
     * @param groupId
     * @Author kdj
     * @Description 判断该用户是否存在在群聊中
     * @Date 2023/7/29 20:54
     * @Return boolean
     */
    @Override
    public boolean isIngroup(int userId, int groupId) {
        int i = joinGroupMapper.isIngroup(userId, groupId);
        return i > 0 ? true : false;
    }

    /**
     * 查询群信息和群成员
     *
     * @return com.zhuiyun.project.api.group.model.GroupModel
     * @author 温
     * @date 2023/7/31 19:07
     * @parameter [groupId]
     * @param groupId 群ID
     *  * @param userId 用户ID
     */
    @Override
    public GroupModel Group(int groupId,int userId) {
        //查询群里的全部成员
        List<User> userss = groupMapper.userss(groupId);
        //查询群的信息
        GroupModel group = groupMapper.Group(groupId,userId);
        group.setUser(userss);
        return group;
    }

    /**
     * @param
     * @Author kdj
     * @Description 获取随机群号
     * @Date 2023/7/24 11:33
     * @Return java.lang.String
     */
    public Long generateUniqueNineDigit() {
        while (true) {
            // 获取当前时间戳（精确到毫秒）
            long timestamp = System.currentTimeMillis();

            // 生成一个9位的随机数
            Random random = new Random();
            int randomNum = random.nextInt(900000000) + 100000000; // 生成范围在100000000到999999999之间的随机数

            // 将时间戳和随机数拼接起来，确保唯一性
            String uniqueNineDigits = String.valueOf(timestamp) + String.valueOf(randomNum);
            uniqueNineDigits = uniqueNineDigits.substring(uniqueNineDigits.length() - 9); // 获取最后的9位数字
            long groupNum = Long.parseLong(uniqueNineDigits);

            // 判断是否之前存在过
            int i = groupMapper.queryNumIsOne(groupNum);
            if (i == 0) {
                // 不存在，返回唯一的9位数字
                return groupNum;
            }
            // 存在，继续循环生成
        }
    }
}
